package com.dengcj.epl.service.ecology.workflow;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dengcj.epl.cache.DefaultCache;
import com.dengcj.epl.cache.TokenCache;
import com.dengcj.epl.entity.ApiResponseResult;
import com.dengcj.epl.entity.ecology.workflow.NewWeaRequest;
import com.dengcj.epl.service.util.EcologyApiUtil;
import com.dengcj.epl.service.util.WorkflowUtil;
import com.dengcj.epl.system.LoadSetting;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dengchunjie
 * @Description: 流程操作类，包含创建、删除等
 * @date 2022/3/9 09:21
 */
public class RequestOperation {

    private EcologyApiUtil ecologyApiUtil = new EcologyApiUtil();


    /**
     * 创建流程
     * @return
     */
    public ApiResponseResult create(NewWeaRequest newWeaRequest){
        if(newWeaRequest.getCreatorId() == null){
            throw new RuntimeException("未设置流程创建人");
        }

        if(newWeaRequest.getWorkflowId() == null){
            throw new RuntimeException("未设置WorkflowId");
        }

        if(StrUtil.isBlank(newWeaRequest.getRequestName())){
            throw new RuntimeException("未设置流程标题");
        }

        if(newWeaRequest.getMainData() == null){
            throw new RuntimeException("未设置主表数据");
        }

        Map paramMap = buildCreateParamMap(newWeaRequest);
        return ecologyApiUtil.commonRequest(newWeaRequest.getCreatorId(), "/api/workflow/paService/doCreateRequest", paramMap);
    }

    /**
     * 删除流程
     * @param operUserId 操作人员Id
     * @param requestId
     * @return
     */
    public ApiResponseResult delete(int operUserId, int requestId){
        Map paramMap = new HashMap();
        paramMap.put("requestId", requestId);

        // 如果是系统管理员，则以监控权限删除流程，其他人员按照权限判断
        if(operUserId == 1){
            JSONObject otherParams = new JSONObject();
            otherParams.set("ismonitor", 1);
            paramMap.put("otherParams",otherParams.toString());
        }

        return ecologyApiUtil.commonRequest(operUserId, "/api/workflow/paService/deleteRequest", paramMap);
    }

    /**
     * 将字段Map转为List
     * @param fieldMap
     * @return
     */
    private List<Map> fieldMap2List(Map fieldMap){
        List<Map> fieldList = new ArrayList<>();

        fieldMap.forEach((k,v) -> {
            Map newFieldMap = new HashMap();
            newFieldMap.put("fieldName", k);
            newFieldMap.put("fieldValue", v);

            fieldList.add(newFieldMap);
        });

        return fieldList;
    }

    private List<Map> buildDtList(int workflowId, List<Map>... dtListArray){
        int len = dtListArray.length;
        String tablename = WorkflowUtil.getTableNameByWorkflowid(workflowId);
        List detailDataList = new ArrayList<>();
        for (int i = 0; i < len; i++) {
            List<Map> dtRowList = dtListArray[i];

            if(dtRowList == null){
                continue;
            }

            int rowCount = dtRowList.size();
            Map dtInfoMap = new HashMap();
            dtInfoMap.put("tableDBName", tablename+"_dt"+(i+1));

            List dtRowsList = new ArrayList<>();
            for (int j = 0; j < rowCount; j++) {
                Map dtRowMap = new HashMap();

                dtRowMap.put("workflowRequestTableFields",fieldMap2List(dtRowList.get(j)));
                dtRowMap.put("recordOrder", 0);
                dtRowsList.add(dtRowMap);
            }

            dtInfoMap.put("workflowRequestTableRecords", dtRowsList);
            detailDataList.add(dtInfoMap);
        }

        return detailDataList;
    }

    /**
     * 构建请求参数Map
     * @param newWeaRequest
     * @return
     */
    private Map buildCreateParamMap(NewWeaRequest newWeaRequest){
        Map paramMap = new HashMap();

        paramMap.put("requestName", newWeaRequest.getRequestName());
        paramMap.put("workflowId", newWeaRequest.getWorkflowId());

        if(newWeaRequest.isAutoCommit()){
            JSONObject otherParams = new JSONObject();
            otherParams.set("isnextflow", 1);
            paramMap.put("otherParams",otherParams.toString());
            paramMap.put("remark",newWeaRequest.getRemark());
        } else {
            JSONObject otherParams = new JSONObject();
            otherParams.set("isnextflow", 0);
            paramMap.put("otherParams",otherParams.toString());
        }

        paramMap.put("mainData", JSONUtil.parseArray(fieldMap2List(newWeaRequest.getMainData())).toString());

        if(newWeaRequest.getDetailData() != null) {
            paramMap.put("detailData", JSONUtil.parseArray(buildDtList(newWeaRequest.getWorkflowId(), newWeaRequest.getDetailData())).toString());
        }

        return paramMap;
    }

    public static void main(String[] args) {
        // 创建流程示例代码
        RequestOperation requestOperation = new RequestOperation();

        // 主表字段
        Map mainFormFieldMap = new HashMap();
        mainFormFieldMap.put("sqr", "1");   // 申请人;
        mainFormFieldMap.put("rq", "2022-03-23");   // 日期;
        mainFormFieldMap.put("nr", "test");   // 内容;
        mainFormFieldMap.put("cjr", "4");   // 创建人;

        // 明细表1字段
        List dt1RowsList = new ArrayList<>();

        for(int i=0; i<4; i++){
            Map dt1RowFieldMap = new HashMap();
            dt1RowFieldMap.put("wpmc", "ceshi01");   // 物品名称
            dt1RowFieldMap.put("sl", "1");   // 数量
            dt1RowFieldMap.put("dj", "123.98");   // 单价

            dt1RowsList.add(dt1RowFieldMap);
        }

        // 明细表3字段
        List dt3RowsList = new ArrayList<>();

        for(int i=0; i<2; i++){
            Map dt3RowFieldMap = new HashMap();
            dt3RowFieldMap.put("mx", "mx001");   // 明细

            dt3RowsList.add(dt3RowFieldMap);
        }

        // ************* 加载配置文件 *************
        DefaultCache.init();
        LoadSetting loadSetting = new LoadSetting();
        loadSetting.execute();
        TokenCache.init();

        NewWeaRequest newWeaRequest = new NewWeaRequest();
        // 创建人
        newWeaRequest.setCreatorId(5);
        // 路径ID
        newWeaRequest.setWorkflowId(3);
        // 请求标题
        newWeaRequest.setRequestName("测试流程2023-01-30");
        // （可选）是否自动提交到下一节点，默认为不自动提交
        newWeaRequest.setAutoCommit(true);
        // （可选）签字意见，仅在自动提交时生效
        newWeaRequest.setRemark("test");
        // 主表字段
        newWeaRequest.setMainData(mainFormFieldMap);
        // （可选）明细表字段 多个明细表按照顺序传，中间有空的明细时需要用null占位
        newWeaRequest.setDetailData(dt1RowsList, null, dt3RowsList);
        // 执行创建
        ApiResponseResult result = requestOperation.create(newWeaRequest);

        System.out.println(result);
    }
}
